package com.github.xzb617.client.route.scg.rules;

import com.github.xzb617.client.route.scg.props.RouteProperties;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import java.util.List;

public class RoutingRuleChain implements RoutingRule {

    private final List<RoutingRule> rules;
    private final int size;
    private int position;

    public RoutingRuleChain(List<RoutingRule> rules) {
        this.rules = rules;
        this.size = rules.size();
        this.position = 0;
    }

    @Override
    public boolean enabled() {
        return true;
    }

    @Override
    public void executeMatches(ServerHttpRequest request, HttpHeaders httpHeaders, String ipAddr, RouteProperties.RuleProperties config, RoutingRule routingRuleChain) {
        if (this.position != this.size) {
            // 调用过滤链中过滤器的执行方法
            ++ this.position;
            RoutingRule nextRule = this.rules.get(this.position - 1);
            nextRule.executeMatches(request, httpHeaders, ipAddr, config, this);
        }
    }

    @Override
    public void matches(ServerHttpRequest request, HttpHeaders httpHeaders, String ipAddr, RouteProperties.RuleProperties config, RoutingRule routingRuleChain) {
        // nothing need to do ...
    }
}
